#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM 5

int tickets=100;

pthread_mutex_t _mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;


void *gettickets(void* args)
{
    char* name=(char*)args;
    while(1)
    {
        pthread_mutex_lock(&_mutex);
        if(tickets>0)
        {
            pthread_cond_wait(&cond,&_mutex);
            tickets--;
            printf("%s 抢到票了，还剩%d\n",name,tickets);
            pthread_mutex_unlock(&_mutex);
        }
        else{
            break;
            pthread_mutex_unlock(&_mutex);
        }
    }
    cout<<"quit ..."<<name<<endl;
    delete name;
    pthread_detach(pthread_self());
    return nullptr;
}


int main()
{
    for(int i=1;i<=NUM;i++)
    {
        pthread_t tid;
        char* ch=new char[64];
        snprintf(ch,64,"thread-%d 号",i);
        pthread_create(&tid,nullptr,gettickets,ch);
    }

    while(1)
    {
        sleep(1);
        // pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
    }
    
    return 0;
}